package com.evolve.autotest;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.evolve.autotest.actions.ActionFactory;
import com.evolve.autotest.actions.ActionsLoader;
import com.evolve.autotest.actions.IAction;
import com.evolve.autotest.util.Configurations;

public class AutoTest {

	private static final String TEST_DIR = "TestDirectory";
	private static final String ACTIONS_DIR = "ActionsDirectory";
	private static final Logger logger = Logger.getLogger(AutoTest.class);
	private ActionFactory actionFactory;
	private ActionsLoader actionsLoader;
	private List<IAction> actionCollection;
	private TestCaseLoader testCaseLoader;
	private List<TestSuite> testCollection;
	private TestRunner testRunner;
	private final List<IResultHandler> outputHandlers;
	
	public AutoTest() {
		actionFactory = new ActionFactory();
		actionsLoader = new ActionsLoader();
		testCaseLoader = new TestCaseLoader(actionFactory);
		testRunner = new TestRunner();
		outputHandlers = new LinkedList<IResultHandler>();
	}
	
	/**
	 * Load actions will load the actions specified in certain directories.
	 */
	public boolean loadActions() {
		String actionsDir = Configurations.getInstance().getProperty(ACTIONS_DIR);
		
		if (actionsDir == null || actionsDir.length() == 0) {
			logger.error("Unable to find the actions directory");
			return false;
		}
	
		actionCollection = actionsLoader.loadActions(actionsDir);
		
		// Add the actions to the factory
		actionFactory.fill(actionCollection);
		
		return true;
	}
	
	/**
	 * Loads all test cases
	 * @return
	 */
	public boolean loadTests() {
		String testDir = Configurations.getInstance().getProperty(TEST_DIR);
		
		if (testDir == null || testDir.length() == 0) {
			logger.error("Unable to find the test cases directory");
			return false;
		}
		
		testCollection = testCaseLoader.loadTestCases(testDir);
		
		return true;
	}

	/**
	 * Runs all tests
	 */
	public void runTests() {	
		
		if (testCollection != null) {
			testRunner.runTestSuites(testCollection);
		} else {
			logger.error("No test suites to run");
		}
	}
	
	/**
	 * Lets the result handles do their job
	 */
	public void handleResults() {
		
		for (IResultHandler outputHandler : outputHandlers) {
			outputHandler.handleResult(testCollection);
		}
	}
}
